/*
 * Copyright 2007-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.paoding.rose.web.instruction;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

/**
 * 
 * @author qieqie.wang@paoding.net
 * 
 */
public class TextInstruction extends AbstractInstruction {

	private String text;
	private String contentType;
	private String encoding;

	public TextInstruction contentType(String contentType) {
		this.contentType = resolvePlaceHolder(contentType);
		return this;
	}

	public String contentType() {
		return contentType;
	}

	public TextInstruction encoding(String encoding) {
		this.encoding = resolvePlaceHolder(encoding);
		return this;
	}

	public String encoding() {
		return encoding;
	}

	public String text() {
		return text;
	}

	public TextInstruction plain(String text) {
		this.text = resolvePlaceHolder(text);
		return this;
	}

	public TextInstruction html(String html) {
		this.text = resolvePlaceHolder(html);
		contentType("text/html");
		return this;
	}

	public TextInstruction xml(String xml) {
		this.text = resolvePlaceHolder(xml);
		contentType("text/xml");
		return this;
	}

	public TextInstruction json(String json) {
		this.text = resolvePlaceHolder(json);
		contentType("text/json");
		return this;
	}

	@Override
	public void render(HttpServletRequest request, HttpServletResponse response) throws IOException {
		if (contentType() != null) {
			response.setContentType(contentType());
		}
		if (encoding() != null) {
			response.setCharacterEncoding(encoding());
		}
		if (StringUtils.isNotBlank(text)) {
			PrintWriter out = response.getWriter();
			out.write(text);
			out.flush();
		}
	}
}
